package com.example.discover

import android.content.Context
import android.util.Log
import com.example.discover.repository.BookDao
import com.example.discover.repository.BookRepository
import com.example.discover.repository.BookWebService
import com.example.discover.viewmodel.BookViewModelFactory
import com.example.featuresdk.HttpClientFactory
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.components.SingletonComponent
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.SupervisorJob
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import javax.inject.Qualifier
import javax.inject.Singleton

@Module
@InstallIn(SingletonComponent::class)
class BookModule {

    @Qualifier
    annotation class BookRetrofit

    @Provides
    @Singleton
    fun bookDatabase(@ApplicationContext context: Context): BookDatabase {
        return BookDatabaseFactory.createDatabase(context, CoroutineScope(SupervisorJob()))
    }

    @Provides
    fun bookDao(bookDatabase: BookDatabase): BookDao {
        return bookDatabase.bookDao()
    }

    @Provides
    fun bookWebService(@BookRetrofit retrofit: Retrofit): BookWebService = retrofit.create(BookWebService::class.java)

    @Provides
    @Singleton
    @BookRetrofit
    fun bookRetrofit(@HttpClientFactory.MockHttpClient httpClient: OkHttpClient) : Retrofit {
        return  Retrofit.Builder()
            .client(httpClient)
            .baseUrl(bookServiceBaseUrl)
            .addConverterFactory(GsonConverterFactory.create())
            .build()
    }

    private val bookServiceBaseUrl = "http://192.168.3.25:8999/"

    @Provides
    fun bookRepository( bookDao: BookDao, bookWebService: BookWebService): BookRepository = BookRepository(bookDao,bookWebService)

    @Provides
    @Singleton
    fun bookViewModelFactory(repository: BookRepository): BookViewModelFactory {

        Log.i("$this","Creating BookViewModelFactory")

        BookViewModelFactory.instance = BookViewModelFactory().apply { this.repository = repository }

        return BookViewModelFactory.instance!!
    }
}